package com.atung.parking.config.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 流量管控
 *
 * @author Administrator
 */
@Component
public class FlowConfigurationHandel {

    @Value("${flow.limiting.max-initialize}")
    private long maxInitialize;
    @Value("${flow.limiting.lock-seconds}")
    private long lockSeconds;
    @Value("${flow.limiting.seconds}")
    private long seconds;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public Boolean currentLimiting(String ip, String url) {
        if (stringRedisTemplate.hasKey(url + ip)) {
            Long increment = stringRedisTemplate.boundValueOps(url + ip).increment(1);
            if (increment > maxInitialize) {
                stringRedisTemplate.opsForValue().set(url + ip, String.valueOf(increment), seconds, TimeUnit.SECONDS);
                return false;
            }
        } else {
            stringRedisTemplate.opsForValue().set(url + ip, String.valueOf(1), seconds, TimeUnit.SECONDS);
        }
        return true;
    }
}
